package org.dq.like.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.dq.like.pojo.ReleaseBoil;
import org.dq.like.pojo.Result;
import org.dq.like.util.MoYuBanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * 摸鱼办控制器
 *
 * @author klh
 * @date 2023/09/12 11:31:11
 */
@Slf4j
@RestController
@RequestMapping("/moyuban")
public class MoYuBanController {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 发布沸点url
     */
    private static final String releaseBoilUrl = "https://api.juejin.cn/content_api/v1/short_msg/publish";

    /**
     * 摸鱼办消息
     */
    @GetMapping("/moyuban")
    public Result<?> moyuban() {
        return Result.OK(MoYuBanUtil.getMoYuMsg());
    }

    /**
     * 发布沸点
     */
    @GetMapping("/releaseBoil")
    public Result<?> releaseBoil(@RequestParam(required = false, value = "content") String content) {
        content = content != null && content != "" ? content : MoYuBanUtil.getMoYuMsg();
        String url = releaseBoilUrl + "?" + JuejinLikeController.getSuffix2();
        ReleaseBoil requestBody = new ReleaseBoil(null, content);
        HttpHeaders headers = new HttpHeaders();
        MediaType mediaType = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(mediaType);
        List<String> cookies = new ArrayList<>();
        cookies.add(JuejinLikeController.cookie1);
        headers.put(HttpHeaders.COOKIE, cookies);
        headers.setOrigin("chrome-extension://lecdifefmmfjnjjinhaennhdlmcaeeeb");
        HttpEntity<String> request = new HttpEntity<String>(JSON.toJSONString(requestBody), headers);
        ResponseEntity<String> resultEntity = restTemplate.postForEntity(url, request, String.class);
        if (resultEntity.hasBody()) {
            JSONObject result = JSONObject.parseObject(resultEntity.getBody());
            return Result.OK(result);
        }
        return Result.OK("请求失败");
    }

}
